export function fetchSource(url: string) {
  return fetch(url).then((res: any) => {
    return res.text();
  });
}

// 递归遍历div的所有子节点
export function foreachDom(parent: Element, cb: (dom: Element) => void) {
  const children = Array.from(parent.children);

  for (let child of children) {
    cb(child);
    foreachDom(child, cb);
  }
}

export function isCssLink(dom: Element) {
  if (dom instanceof HTMLLinkElement) {
    if (dom.getAttribute("rel") === "stylesheet") return true;
  }
  return false;
}

export function isCssInner(dom: Element) {
  if (dom instanceof HTMLStyleElement) {
    return true;
  }
  return false;
}

// 是否是外连标签
// <script src="..." />
export function isScriptSrc(dom: Element) {
  if (dom instanceof HTMLScriptElement) {
    const src = dom.getAttribute("src");
    if (src) return true;
  }
  return false;
}

// 是否是内连标签
// <script>... code ...</script>
export function isScriptCode(dom: Element) {
  if (dom instanceof HTMLScriptElement) {
    const src = dom.getAttribute("src");
    const code = dom.textContent;
    if (!src && code) return true;
  }
  return false;
}

// /static/js/bundle.js ----> http://localhost:3000/static/js/bundle.js
export function fillUrl(url: string, base: string) {
  if (url.includes("http")) {
    return url;
  }
  // 去掉头部'/': /static/js/bundle.js --> static/js/bundle.js
  if (url.startsWith("/")) {
    url = url.substring(1, url.length);
  }
  // 去掉尾部'/':  http://localhost:3000/ --> http://localhost:3000
  if (base.endsWith("/")) {
    base = base.substring(0, base.length - 1);
  }
  return `${base}/${url}`;
}

// 是否是构造函数
export function isConstructor(fn: Function) {
  const str = fn.toString();
  if (/^function\s+[A-Z]/.test(str)) return true;
  return false;
}

// 是否是class
export function isClass(fn: Function) {
  const str = fn.toString();
  if (/^class\s+/.test(str)) return true;
  return false;
}
